package com.youku.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.jcs.JCS;
import org.apache.commons.jcs.access.CacheAccess;
import org.apache.commons.jcs.engine.behavior.ICacheElement;

import com.youku.model.LogModel;

public class JCSClient {

	private static Map<String, CacheAccess<String, List<LogModel>>> cacheMap = new HashMap<>();

	public static synchronized void set(String region, String key, LogModel value) {
		List<LogModel> values = getJCSInstance(region).get(key);
		if (values == null) {
			values = new ArrayList<>();
		}
		values.add(value);
		getJCSInstance(region).put(key, values);
	}

	public static synchronized List<LogModel> get(String region, String key) {
		List<LogModel> values = getJCSInstance(region).get(key);
		if (values == null) {
			return Collections.emptyList();
		} else {
			return values;
		}
	}

	public static synchronized void remove(String region, String key) {
		getJCSInstance(region).remove(key);
	}

	public static synchronized void clear(String region) {
		getJCSInstance(region).clear();
	}

	public static synchronized CacheAccess<String, List<LogModel>> getJCSInstance(String region) {
		CacheAccess<String, List<LogModel>> cache = cacheMap.get(region);
		if (cache == null) {
			cache = JCS.getInstance(region);
			cacheMap.put(region, cache);
		}
		return cache;
	}

	public static synchronized String listAll() {
		Map<String, Map<String, String>> memData = new HashMap<>();
		for (Entry<String, CacheAccess<String, List<LogModel>>> cacheAccessEntry : cacheMap.entrySet()) {
			String cacheAccessKey = cacheAccessEntry.getKey();
			CacheAccess<String, List<LogModel>> cacheAccess = cacheAccessEntry.getValue();

			Map<String, String> map = new HashMap<>();
			for (Entry<String, ICacheElement<String, List<LogModel>>> cacheElementEntry : cacheAccess
					.getCacheElements(cacheAccess.getCacheControl().getKeySet()).entrySet()) {
				ICacheElement<String, List<LogModel>> cacheElement = cacheElementEntry.getValue();

				map.put(cacheElement.getKey(), String.valueOf(cacheElement.getVal()));
			}

			if (!map.isEmpty()) {
				memData.put(cacheAccessKey, map);
			}

		}
		return JsonHelper.toJsonString(memData);
	}

}
